package com.github.thinwonton.showcase.springboot.security.security.support;

import com.github.thinwonton.showcase.springboot.security.po.SystemRole;
import com.github.thinwonton.showcase.springboot.security.po.SystemUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * security中的用户描述
 *
 * @author hugo
 * @date 2018/7/13
 */
public class SystemUserDetails extends SystemUser implements UserDetails {

    public SystemUserDetails(SystemUser systemUser) {
        if (systemUser != null) {
            this.setId(systemUser.getId());
            this.setUserName(systemUser.getUserName());
            this.setPassword(systemUser.getPassword());
            this.setCreateTime(systemUser.getCreateTime());
            this.setSystemRoleSet(systemUser.getSystemRoleSet());
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new HashSet<>();
        Set<SystemRole> systemRoleSet = this.getSystemRoleSet();
        if (systemRoleSet != null) {
            systemRoleSet.forEach(
                    systemRole -> {
                        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(systemRole.getRoleName());
                        authorities.add(authority);
                    });
        }
        return authorities;
    }

    @Override
    public String getUsername() {
        return super.getUserName();
    }

    @Override
    public String getPassword() {
        return super.getPassword();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
